package nickthissen.iracing.common;

import nickthissen.iracing.datamodels.Result;
import nickthissen.iracing.networking.NetworkMethod;
import nickthissen.iracing.networking.Networking;

import android.content.Context;
import android.os.AsyncTask;
import android.util.Log;


/**
 * @author nthissen
 *
 * Encapsulates a data-loading operation performed in a background thread.
 *
 * @param <T> Type of input argument
 */
public class Task<T> extends AsyncTask<T, Void, Result>
{
    private Context context;
	private DataLoader<T> loader;
	private OnFinishedListener finishedListener;
	
	public Task(Context c, DataLoader<T> dataLoader)
	{
		loader = dataLoader;
		loader.setContext(c);
	}
	
	@Override
	protected Result doInBackground(T... arg0)
	{
		if (arg0.length > 0)
			return loader.getData(arg0[0]);
		return loader.getData(null);
	}
	
	@Override
	protected void onPostExecute(Result out)
	{
		loader.onFinished(out);
		if (finishedListener != null) finishedListener.finished();
	}

    @Override
    protected void onCancelled()
    {
        // Cancel client requests, if any
        //NetworkMethod.getClient().cancelRequests(context, true);
        //Log.i("Task", "Task and client cancelled.");
        super.onCancelled();
    }

    public void setOnFinishedListener(OnFinishedListener listener)
	{
		finishedListener = listener;
	}
	
	public interface OnFinishedListener
	{
		public void finished();
	}
}
